package com.dtkavin.threads;

import java.util.Random;
import java.util.concurrent.*;

/**
 * Created by john on 10/3/16.
 * 相当于一组Callable，通过take获取Callable，哪个先跑完，获取哪个的结果
 */
public class CompletionServiceDemo {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        CompletionService completionService = new ExecutorCompletionService(executorService);
        for (int i = 0; i < 10; i++) {
            completionService.submit(new Callable() {
                public Object call() throws Exception {
                    Thread.sleep(new Random().nextInt(5000));//随机睡眠
                    return "result: " + Thread.currentThread().getName();
                }
            });
        }
        for (int i = 0; i < 10; i++) {
            try {
                System.out.println(completionService.take().get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
}
